import type { Router, RouteRecordRaw } from 'vue-router';

import { usePermissionStoreWithOut } from '/@/shared/store/vbenModules/permission';

import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';

import { authRouteGuard } from '/@/shared/auth';
import DynamicRoute from '/@/routes/dynamic-route';
import appSessionService from '/@/shared/abp/app-session.service';

export function createPermissionGuard(router: Router) {
  authRouteGuard.init(router);
  const permissionStore = usePermissionStoreWithOut();

  router.beforeEach(async (to, from, next) => {
    if (permissionStore.getIsDynamicAddedRoute) {
      next();
      return;
    }
    if (appSessionService.user) {
      await DynamicRoute.getDynamicMenuList();
    }

    const routes = await permissionStore.buildRoutesAction();
    routes.forEach((route) => {
      router.addRoute(route as unknown as RouteRecordRaw);
    });

    router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);

    permissionStore.setDynamicAddedRoute(true);

    if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
      // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
      // next(PageEnum.BASE_HOME);
      next({ path: to.fullPath, replace: true, query: to.query });
    } else {
      const redirectPath = (from.query.redirect || to.path) as string;
      const redirect = decodeURIComponent(redirectPath);
      const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
      next(nextData);
    }
  });
}
